﻿using System;
using System.Diagnostics;
using System.Reflection;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

using Microsoft.SharePoint.Administration.Claims;

using System.Linq;

using AgileShare.Framework.Core;

namespace AgileShare.Framework.Library.Helpers
{
    /// <summary>
    /// This class contains helper methods for working with SharePoint Webs
    /// - All methods should be static
    /// - DO NOT USE SPContext
    /// </summary>
    public class SPWebHelper
    {
        /// <summary>
        /// Determines whether or not the SPWeb object contains a list (or lists) with the specified title (case insensitive).
        /// </summary>
        /// <param name="web">The SPWeb object.</param>
        /// <param name="listTitle">The title of the list.</param>
        /// <returns>Boolean</returns>
        public static bool HasList(SPWeb web, string listTitle)
        {
            return web.Lists.Cast<SPList>().Any(list => list.Title.Equals(listTitle, StringComparison.CurrentCultureIgnoreCase));
        }

        /// <summary>
        /// Determines whether or not the SPWeb object contains a list with the specified ID.
        /// </summary>
        /// <param name="web">The SPWeb object.</param>
        /// <param name="listId">The list Guid.</param>
        /// <returns>Boolean</returns>
        public static bool HasList(SPWeb web, Guid listId)
        {
            return web.Lists.Cast<SPList>().Any(list => list.ID.Equals(listId));
        }

        /// <summary>
        /// Checks if a web exists with the given name in the site.
        /// </summary>
        /// <param name="webName">Name of the web.</param>
        /// <param name="site">The site.</param>
        /// <returns></returns>
        public static bool WebExists(string webName, SPSite site)
        {
            bool exists = false;

            try
            {
                exists = site.AllWebs[webName].Exists;
            }
            catch
            {
                // Not necessary to trace
            }

            return exists;
        }


        /// <summary>
        /// Tries the get web.
        /// </summary>
        /// <param name="webName">Name of the web.</param>
        /// <param name="site">The site.</param>
        /// <returns></returns>
        public static SPWeb TryGetWeb(string webName, SPSite site)
        {
            SPWeb web = null;

            try
            {
                web = site.AllWebs[webName];
            }
            catch (Exception ex)
            {
                string errorMessage = string.Format("Web not found at site '{0}' with name '{1}'.", site.Url, webName);
                TraceProvider.Log(errorMessage, TraceProviderCategories.Default, (uint)TraceProviderEventIds.SPWebHelper, TraceProviderSeverity.Information, ex);
            }

            return web;
        }
    }
}
